package cn.com.generaldata.os.service.common;

import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import cn.com.generaldata.os.constant.FilterConstant;
import cn.com.generaldata.os.dao.intf.BaseDAOInterface;
import cn.com.generaldata.os.paging.Filter;
import cn.com.generaldata.os.paging.FilterRule;
import cn.com.generaldata.os.paging.Page;
import cn.com.generaldata.os.pojo.Area;
import cn.com.generaldata.os.pojo.Pm;
import cn.com.generaldata.os.pojo.ReportAttach;
import cn.com.generaldata.os.pojo.Unit;
import cn.com.generaldata.os.pojo.User;
import cn.com.generaldata.os.vo.ResultVO;

@Component
public abstract class AbstractPmService {

	private static Logger log = LoggerFactory.getLogger(AbstractPmService.class);

	@Autowired
	@Qualifier("baseDAO")
	protected BaseDAOInterface<Pm> pmDAO;

	@Autowired
	@Qualifier("baseDAO")
	protected BaseDAOInterface<Area> areaDAO;

	@Autowired
	@Qualifier("baseDAO")
	protected BaseDAOInterface<Unit> unitDAO;

	@Autowired
	@Qualifier("baseDAO")
	protected BaseDAOInterface<User> userDAO;

	@Autowired
	@Qualifier("baseDAO")
	protected BaseDAOInterface<ReportAttach> reportAttachDAO;

	/**
	 * 取得自己的消息列表.
	 */
	public ResultVO<Pm> getPmList(String toUserId, int curPage) {
		// 查询
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("sendTime");
//		User user = userDAO.get(User.class, toUserId);
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "pmTo", toUserId));

		Page page = new Page();
		page.setPageNumber(curPage);
		page.setPageSize(ResultVO.DEFAULT_PAGE_SIZE);
		Properties properties = new Properties();
		java.io.InputStream inputstream = getClass().getResourceAsStream("/fileupload.properties");
		try {
			properties.load(inputstream);
		} catch (Exception ex) {
			System.out.print(ex);
		}
		List<Pm> resultList = pmDAO.find(Pm.class, filter, page);
		for (Pm p : resultList) {
			User user = userDAO.get(User.class, p.getPmFrom());
			p.setPmFromName(user.getUserUnit().getUnitName()); // 单位名称

		}

		// 计数
		int count = pmDAO.count(Pm.class, filter);

		// 返回
		return new ResultVO<Pm>(resultList, page.getPageSize(), curPage, count);
	}

	/**
	 * 根据企业名称检索企业.
	 */
	abstract public List<Unit> queryCompanyByName(String name, String uid);

	/**
	 * 发送PM给多个人.
	 */
	public void sendPm(String fromUserId, String toUserIdStr, String title, String content, String fujian) {
		// 多个收件人，逗号分隔
		String[] toUserIdArray = toUserIdStr.split(",");
		for (String toUserId : toUserIdArray) {
			if (toUserId.trim().length() == 0) {
				continue;
			}

			// 创建消息并保存
			Pm pm = new Pm();
			pm.setPid("0"); // pid是0的，说明是主消息，而不是主消息下的回复消息
			pm.setPmFrom(fromUserId);
			pm.setPmTo(toUserId);
			pm.setTitle(title);
			pm.setContent(content);
			pm.setIsRead(0);
			if (StringUtils.isNotBlank(fujian)) {
				pm.setFujian(fujian);
			}
			pm.setSendTime(new Date());
			pm.setId(UUID.randomUUID().toString().replaceAll("-", ""));
			pmDAO.save(pm);

		}
	}

	/**
	 * 设置为已读.
	 */
	public void setPmRead(String pmId) {
		Pm pm = pmDAO.get(Pm.class, pmId);
		if (pm != null) {
			pm.setIsRead(1);
			pm.setReadTime(new Date());
			pmDAO.update(pm);
		}
	}

	/**
	 * 按企业名称查询的结果数.
	 */
	abstract public int countCompanyByName(String name, String role);

	public boolean existUnReadPms(String userId, Page page) {
		if (StringUtils.isBlank(userId)) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			log.error("userId为空");
			return false;
		}

		List<Pm> billboardUsers = queryUnReadStatus(userId, page);

		if (billboardUsers.size() > 0) {
			// System.out.println(billboardUsers.size());
			return true;
		} else {
			return false;
		}
	}

	public List<Pm> queryUnReadStatus(String userId, Page page) {
		if (StringUtils.isBlank(userId)) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			log.error("userId为空");
			return null;
		}

		Filter filter = new Filter();
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "pmTo", userId));
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "isRead", 0));

		List<Pm> pms = pmDAO.find(Pm.class, filter, null);

		return pms;
	}

	/**
	 * 取得自己的消息列表.
	 */
	public List<Pm> getAllPmList(String toUserId) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.DESC);
		filter.setSortBy("sendTime");
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "pmTo", toUserId));

		List<Pm> resultList = pmDAO.find(Pm.class, filter, null);
		return resultList;
	}
	
	public Pm queryPmById(String id) {// 2014-9-12
		if (id != null) {
			Pm tPm = pmDAO.get(Pm.class, id);
			User user = userDAO.get(User.class, tPm.getPmFrom());
			tPm.setPmFromName(user.getUserUnit().getUnitName()); // 单位名称
			return tPm;
		} else {
			return null;
		}
	}
}
